package com.ebt.m.share;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.thirtylogin.ShareBlock;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareContentWebpage;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareListener;
import com.ebt.m.commons.buscomponent.thirtylogin.qq.QQShareManager;
import com.ebt.m.commons.buscomponent.thirtylogin.wechat.WechatShareManager;
import com.ebt.m.commons.utils.ClipBoardUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.utils.ConfigData;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.ArrayList;
import java.util.List;

public class ShareDialog extends Dialog implements android.view.View.OnClickListener {

    public static final String COPY_LINK = "COPY_LINK";
    public static final String WE_CHAT = "Wechat";
    public static final String WE_CHAT_MOMENTS = "WechatMoments";
    public static final String QQ = "QQ";
    public static final String QZONE = "QZone";

    private Button share_dialog_label_cancel;


    private String mPlatform;
    private Activity mActivity;

    private OnBeforeShareListener mBeforeShareListener;

    protected ShareDialog(Context context) {
        super(context, R.style.dialog);
        if (context instanceof Activity) {
            mActivity = (Activity) context;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_dialog);
        initWindow();
        initView();
        setupListener();
        initThirtyShareData();
    }

    private void initThirtyShareData() {
        ShareBlock.getInstance().initQQ(ConfigData.QQ_APPID);
        ShareBlock.getInstance().initWechat(ConfigData.WECHAT_APPID, ConfigData.WECHAT_SECRET);
    }

    public void initWindow() {
        Window win = this.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        win.setAttributes(lp);
        this.setCanceledOnTouchOutside(true);
    }

    private void initView() {
        share_dialog_label_cancel = (Button) findViewById(R.id.share_dialog_label_cancel);
        List<String> hideList = W.hidePlatformList;
        if (hideList != null && hideList.size() > 0) {
            for (int i = 0; i < hideList.size(); i++) {
                String platform = hideList.get(i);
                if (WE_CHAT.equalsIgnoreCase(platform)) {
                    findViewById(R.id.share_unit_wechat).setVisibility(View.GONE);
                } else if (COPY_LINK.equalsIgnoreCase(platform)) {
                    findViewById(R.id.share_unit_copy_link).setVisibility(View.GONE);
                } else if (WE_CHAT_MOMENTS.equalsIgnoreCase(platform)) {
                    findViewById(R.id.share_unit_weichatfriends).setVisibility(View.GONE);
                } else if (QQ.equalsIgnoreCase(platform)) {
                    findViewById(R.id.share_unit_qq).setVisibility(View.GONE);
                } else if (QZONE.equalsIgnoreCase(platform)) {
                    findViewById(R.id.share_unit_qzone).setVisibility(View.GONE);
                }
            }
        }
        findViewById(R.id.share_unit_wechat).setOnClickListener(this);
        findViewById(R.id.share_unit_copy_link).setOnClickListener(this);
        findViewById(R.id.share_unit_weichatfriends).setOnClickListener(this);
        findViewById(R.id.share_unit_qq).setOnClickListener(this);
        findViewById(R.id.share_unit_qzone).setOnClickListener(this);
    }

    private void setupListener() {
        share_dialog_label_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_dialog_label_cancel:
                this.dismiss();
                return;
            case R.id.share_unit_wechat:
                mPlatform = WE_CHAT;
                break;
            case R.id.share_unit_copy_link:
                mPlatform = COPY_LINK;
                break;
            case R.id.share_unit_weichatfriends:
                mPlatform = WE_CHAT_MOMENTS;
                break;
            case R.id.share_unit_qq:
                mPlatform = QQ;
                break;
            case R.id.share_unit_qzone:
                mPlatform = QZONE;
                break;
            default:
                return;
        }
        showShareByPlatform(mPlatform, W);
    }

    private void shareToQQ(Wrapper wrapper) {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, wrapper.title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, wrapper.content);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, wrapper.gotoUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, wrapper.localImagePath);

        QQShareManager qqShareManager = new QQShareManager(mActivity);
        if (wrapper.shareListener != null) {
            wrapper.shareListener.setPlatform(QQ);
        }
        if (mActivity != null) {
            doBeforeShare();
            qqShareManager.shareToQQ(params, wrapper.shareListener);
        }
    }

    private void shareToQZone(Wrapper wrapper) {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, wrapper.title);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, wrapper.content);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, wrapper.gotoUrl);//必填
        ArrayList<String> localImagePaths = new ArrayList<>();
        localImagePaths.add(wrapper.localImagePath);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, localImagePaths);
        QQShareManager qqShareManager = new QQShareManager(mActivity);
        if (wrapper.shareListener != null) {
            wrapper.shareListener.setPlatform(QZONE);
        }
        if (mActivity != null) {
            doBeforeShare();
            qqShareManager.shareToQZone(params, wrapper.shareListener);
        }
    }

    private void showShareByPlatform(String platform, Wrapper w) {
        if (w != null) {
            if (QQ.equals(platform)) {
                shareToQQ(w);
            } else if (COPY_LINK.equals(platform)) {
                copyLink(w);
            } else if (QZONE.equals(platform)) {
                shareToQZone(w);
            } else if (WE_CHAT.equals(platform)) {
                shareToWechat(w);
            } else if (WE_CHAT_MOMENTS.equals(platform)) {
                shareToWechatMoments(w);
            }
        }
    }

    private void copyLink(Wrapper w) {
        if (w == null) {
            return;
        }
        String url = w.gotoUrl;
        ClipBoardUtil.copy(mActivity, url);
        ToastUtil.show(mActivity,"链接已复制!");
        dismiss();
    }

    private void shareToWechat(Wrapper w) {
        wechatShare(w, SendMessageToWX.Req.WXSceneSession);
    }

    private void shareToWechatMoments(Wrapper w) {
        wechatShare(w, SendMessageToWX.Req.WXSceneTimeline);
    }

    private void wechatShare(Wrapper w, int scene) {
        WechatShareManager wechatShareManager = new WechatShareManager(mActivity);
        String url;
        if (scene == SendMessageToWX.Req.WXSceneTimeline) {
            url = w.gotoUrl;
        } else {
            url = w.gotoUrlForWechat == null ? w.gotoUrl : w.gotoUrlForWechat;
        }
        if (w.shareListener != null) {
            switch (scene) {
                case SendMessageToWX.Req.WXSceneSession:
                    w.shareListener.setPlatform(WE_CHAT);
                    break;
                case SendMessageToWX.Req.WXSceneTimeline:
                    w.shareListener.setPlatform(WE_CHAT_MOMENTS);
                    break;
            }
        }
        doBeforeShare();
        wechatShareManager.share(new ShareContentWebpage(w.title, w.content, url, w.localImagePath), scene, w.shareListener);
    }

    public void doBeforeShare() {
        if (W.beforeShareListener != null) {
            W.beforeShareListener.doBeforeShare();
        }
    }

    private static class Wrapper {
        public String title;
        public String content;
        public String gotoUrl;
        public String gotoUrlForWechat;
        public String localImagePath;
        public List<String> hidePlatformList;
        public Context context;
        public ShareListener shareListener;
        public boolean closeAfterSuccess;
        public OnBeforeShareListener beforeShareListener;
    }

    public static class Builder {
        private final Wrapper wrapper;

        public Builder(Context context) {
            wrapper = new Wrapper();
            wrapper.context = context;
        }

        public Builder setShareTitle(String title) {
            wrapper.title = title;
            return this;
        }

        /**
         * 待隐藏的list
         *
         * @param platforms
         * @return
         */
        public Builder setHidePlatformList(List<String> platforms) {
            wrapper.hidePlatformList = platforms;
            return this;
        }

        public Builder setShareContent(String content) {
            wrapper.content = content;
            return this;
        }

        public Builder setShareUrl(String gotoUrl) {
            wrapper.gotoUrl = gotoUrl;
            return this;
        }

        public Builder setShareUrlWeXin(String gotoUrlForWechat) {
            wrapper.gotoUrlForWechat = gotoUrlForWechat;
            return this;
        }

        public Builder setShareImagePath(String localImagePath) {
            wrapper.localImagePath = localImagePath;
            return this;
        }

        public Builder setShareListener(ShareListener listener) {
            wrapper.shareListener = listener;
            return this;
        }

        public Builder setDialogDismissIfShareSuccess() {
            wrapper.closeAfterSuccess = true;
            return this;
        }

        public Builder setBeforeShareListener(OnBeforeShareListener listener) {
            wrapper.beforeShareListener = listener;
            return this;
        }

        public ShareDialog create() {
            ShareDialog shareDialog = new ShareDialog(wrapper.context);
            shareDialog.setWrapper(wrapper);
            shareDialog.initWrapper(wrapper);
            return shareDialog;
        }

    }

    private Wrapper W;

    private void setWrapper(Wrapper w) {
        W = w;
    }

    private void initWrapper(Wrapper w) {
        if (w != null) {
            if (w.closeAfterSuccess && w.shareListener != null) {
                w.shareListener.setDialog(this);
            }
        }
    }

    public static int dip2px(Context context, float dpValue) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) (dpValue * metrics.density + 0.5f);
    }


    public void setBeforeShareListener(OnBeforeShareListener listener) {
        mBeforeShareListener = listener;
    }

    public interface OnBeforeShareListener {
        /**
         * 分享之前做什么？
         * 用于在分享时（满足分享条件的前提下），将计划书发送的消息传到服务端
         */
        void doBeforeShare();
    }

}